package com.qidianit.mes.pro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.pro.Process;
import com.qidianit.mes.pojo.pro.WorkflowProcess;
import com.qidianit.mes.pro.mapper.DictDataMapper;
import com.qidianit.mes.pro.mapper.ProcessMapper;
import com.qidianit.mes.pro.mapper.WorkflowMapper;
import com.qidianit.mes.pro.mapper.WorkflowProcessMapper;
import com.qidianit.mes.pro.service.WorkflowProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @Author: wang fei long
 * @Date: 2025/9/18 0018 - 19:29
 */
@Service
public class WorkflowProcessServiceImpl implements WorkflowProcessService {
    @Autowired
    private WorkflowProcessMapper workflowProcessMapper;

    @Autowired
    private ProcessMapper processMapper;

    @Autowired
    private DictDataMapper dictDataMapper;

    @Override
    public Result<PageInfo<WorkflowProcess>> selectList(Long workflowId, int pageNum, int pageSize) {
       PageHelper.startPage(pageNum,pageSize);
       //查询关系对象列表
        List<WorkflowProcess> workflowProcesses= workflowProcessMapper.selectList(workflowId);
        //
        for(WorkflowProcess wp : workflowProcesses){
            //查询当前工序
           wp.setProcess( processMapper.selectById(wp.getProcessId()));
           //查询下一道工序
            //查询当前工艺的所有工序，按照顺序排序，根据当前工序找到下一个工序
            //查询当前工序的所有工序
            List<Process> processes=processMapper.selectProcessByWorkflowId(wp.getId());
            Process nextProcess=getNextProcess(processes,wp.getProcess());
            wp.setNextProcess(nextProcess);
            //查询与下一道工序关系的字典信息
            wp.setRelationNextDict(dictDataMapper.selectById(wp.getRelationNext()));
        }
        return Result.success(new PageInfo<>(workflowProcesses));
    }
    @Override
    public Result<WorkflowProcess> saveWorkflowProcess(WorkflowProcess workflowProcess) {
        if (isStepOrderExist(workflowProcess.getWorkflowId(), workflowProcess.getStepOrder(), null)) {
            return Result.error("工序序号[" + workflowProcess.getStepOrder() + "]已经存在");
        }
        // 校验2：工序是否已存在于当前工艺中
        if (isProcessExist(workflowProcess.getWorkflowId(), workflowProcess.getProcessId(), null)) {
            Process process = processMapper.selectById(workflowProcess.getProcessId());
            return Result.error("工序" + process.getProcessName() + "已经存在");
        }
        // 执行新增
        int rows = workflowProcessMapper.saveWorkflowProcess(workflowProcess);
        return rows > 0 ? Result.success() : Result.error("操作失败");
    }

    @Override
    public Result<WorkflowProcess> selectById(Long id) {
        return Result.success(workflowProcessMapper.selectById(id));
    }

    @Override
    public Result<WorkflowProcess> updateById(WorkflowProcess workflowProcess) {
        if (isStepOrderExist(workflowProcess.getWorkflowId(), workflowProcess.getStepOrder(), workflowProcess.getId())) {
            return Result.error("工序序号[" + workflowProcess.getStepOrder() + "]已经存在");
        }
        // 校验2：工序是否已存在于当前工艺中（排除当前ID）
        if (isProcessExist(workflowProcess.getWorkflowId(), workflowProcess.getProcessId(), workflowProcess.getId())) {
            Process process = processMapper.selectById(workflowProcess.getProcessId());
            return Result.error("工序" + process.getProcessName() + "已经存在");
        }
        // 执行更新
        int rows = workflowProcessMapper.updateById(workflowProcess);
        return rows > 0 ? Result.success() : Result.error("操作失败");
    }

    @Override
    public Result deleteById(Long id) {
        return  workflowProcessMapper.deleteById(id)==1? Result.success():Result.error("操作失败");
    }

    @Override
    public Result batchDelete(Long[] ids) {
        return workflowProcessMapper.batchDelete(ids)>0? Result.success():Result.error("操作失败");
    }


    private boolean isStepOrderExist(Long workflowId, Integer stepOrder, Long excludeId) {
        List<WorkflowProcess> list = workflowProcessMapper.selectByWorkflowIdAndStepOrder(workflowId, stepOrder);
        if (list.isEmpty()) {
            return false;
        }
        // 编辑时排除自身
        if (excludeId != null) {
            return list.stream().anyMatch(item -> !item.getId().equals(excludeId));
        }
        return true;
    }

    // 辅助方法：校验工序是否已存在于当前工艺
    private boolean isProcessExist(Long workflowId, Long processId, Long excludeId) {
        List<WorkflowProcess> list = workflowProcessMapper.selectByWorkflowIdAndProcessId(workflowId, processId);
        if (list.isEmpty()) {
            return false;
        }
        // 编辑时排除自身
        if (excludeId != null) {
            return list.stream().anyMatch(item -> !item.getId().equals(excludeId));
        }
        return true;
    }

    private Process getNextProcess(List<Process> processes,Process process){
        //从processes找到process的下一道工序，没有返回null
        for(int i=0;i<processes.size()-1;i++){
            if(processes.get(i).getId().equals(process.getId())&&processes.get(i+1)!=null){
                return processes.get(i+1);
            }
        }
        return null;
    }
}
